package com.lm.generator.controller;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lm.common.core.util.R;
import com.lm.generator.entity.GenQo;
import com.lm.generator.entity.TableInfo;
import com.lm.generator.service.IGenService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 代码生成
 *
 * @author lm
 * @date 2019/7/31 10:15
 */
@Controller
@RequestMapping("/gen")
public class GenController {

    @Autowired
    private IGenService genService;

    /**
     * 列表
     *
     * @param tableName 参数集
     * @return 数据库表
     */
    @GetMapping("/page")
    public R<IPage> list(Page page, TableInfo tableName) {
        return R.success(genService.queryPage(page, tableName));
    }

    /**
     * 生成代码
     */
    @RequestMapping("/genCode/{tableName}")
    @ResponseBody
    public void genCode(HttpServletResponse response, @PathVariable("tableName") String tableName, GenQo genConfig) throws IOException {
        byte[] data = genService.generatorCode(tableName, genConfig);
        genCode(response, data);
    }

    /**
     * 批量生成代码
     */
    @RequestMapping("/batchGenCode")
    @ResponseBody
    public void batchGenCode(HttpServletResponse response, String tables, GenQo genConfig) throws IOException {
        String[] tableNames = Convert.toStrArray(tables);
        byte[] data = genService.generatorCode(tableNames, genConfig);
        genCode(response, data);
    }

    /**
     * 生成zip文件
     *
     * @param response
     * @param data
     * @throws IOException
     */
    private void genCode(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"scm.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}
